package NewCoder;

import java.util.*;

public class BM41 {
    Map<Integer,Integer> map=new HashMap<>();
    int[] pre;
    public int[] solve (int[] xianxu, int[] zhongxu) {
        // write code here
        if(xianxu.length==0) return new int[0];
        this.pre=xianxu;
        int n=zhongxu.length;
        for(int i=0;i<n;i++){
            map.put(zhongxu[i],i);
        }
        TreeNode root=build(0,0,n-1);
        ArrayList<Integer> res=rightView(root);
        int[] arr=new int[res.size()];
        for(int i=0;i<arr.length;i++){
            arr[i]=res.get(i);
        }
        return arr;
    }
    private ArrayList<Integer> rightView(TreeNode root){
        ArrayList<Integer> list=new ArrayList<>();
        Queue<TreeNode> q=new LinkedList<>();
        q.offer(root);
        while(!q.isEmpty()){
            int size=q.size();
            while(size--!=0){
                TreeNode tmp=q.poll();
                if(tmp.left!=null){
                    q.offer(tmp.left);
                }
                if(tmp.right!=null){
                    q.offer(tmp.right);
                }
                if(size==0){
                    list.add(tmp.val);
                }
            }
        }
        return list;
    }
    private TreeNode build(int root,int left,int right){
        if(left>right) return null;
        TreeNode node=new TreeNode(pre[root]);
        int i=map.get(pre[root]);
        node.left=build(root+1,left,i-1);
        node.right=build(root+i-left+1,i+1,right);
        return node;
    }
}
